package com.yy.jhl.ui.manager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.yy.common.base.BaseActivity;
import com.yy.common.commonutils.SPUtils;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonwidget.LoadingDialog;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;
import com.yy.jhl.app.MyApplication;
import com.yy.jhl.bean.FileInfo;
import com.yy.jhl.bean.InviteBatchInfo;
import com.yy.jhl.bean.InvitePackageInfo;
import com.yy.jhl.bean.LoginInfo;
import com.yy.jhl.interfaces.FileUploadCallBack;
import com.yy.jhl.ui.manager.contract.MainWithCodeContract;
import com.yy.jhl.ui.manager.presenter.MainWithCodePresenter;
import com.yy.jhl.ui.qrcode.QRScanActivity;
import com.yy.jhl.ui.user.activity.LoginSelectActivity;
import com.yy.jhl.util.DataRequestUtil;
import com.yy.jhl.util.DataUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by libingn on 2017/12/9.
 */

public class MainWithCodeActivity extends BaseActivity<MainWithCodePresenter> implements MainWithCodeContract.View {
    @BindView(R.id.upload_history_text)
    TextView uploadHistoryText;
    @BindView(R.id.back_text)
    TextView backText;
    @BindView(R.id.code_history_text)
    TextView codeHistoryText;
    @BindView(R.id.logout_text)
    TextView logoutText;
    @BindView(R.id.menu_parent)
    LinearLayout menuParent;
    @BindView(R.id.enter_code_text)
    TextView enterCodeText;
    @BindView(R.id.flashlights_text)
    TextView flashlightsText;
    @BindView(R.id.back_menu_img)
    ImageView backMenuImg;
    @BindView(R.id.scan_img)
    ImageView scanImg;
    @BindView(R.id.mapview)
    MapView mapview;
    @BindView(R.id.code_edit)
    EditText codeEdit;
    @BindView(R.id.ensure_btn)
    Button ensureBtn;
    @BindView(R.id.enter_code_parent)
    LinearLayout enterCodeParent;
    @BindView(R.id.bottom_menu_parent)
    LinearLayout bottomMenuParent;
    @BindView(R.id.order_name_text)
    TextView orderNameText;
    @BindView(R.id.order_code_text)
    TextView orderCodeText;
    @BindView(R.id.order_batch_text)
    TextView orderBatchText;
    @BindView(R.id.order_num_text)
    TextView orderNumText;
    @BindView(R.id.main_with_code_title)
    TextView tvTitle;
    @BindView(R.id.hint_text)
    TextView hintText;
    @BindView(R.id.content_view)
    View contentView;
    private BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    LocationClient mLocClient;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    String upload_completed = "0";
    @Override
    public int getLayoutId() {
        return R.layout.act_main_with_code;
    }

    @Override
    public void initView() {
        scanImg.setClickable(false);
        bottomMenuParent.getBackground().mutate().setAlpha(180);
        initBaiDuMap();
        LoginInfo.UserBean userInfo = DataUtil.getUserInfo(mContext);
        LoginInfo.UserBean.CompanyBean company = userInfo.getCompany();
        switch (company.getType()){
            case "1":
                tvTitle.setText("国内货代");
                break;
            case "2":
                tvTitle.setText("国外货代");
                break;
            case "3":
                tvTitle.setText("到货验收");
                break;
        }
    }

    @Override
    protected void onResume() {
        mPresenter.getBatchCode();
        super.onResume();
    }

    @OnClick({R.id.upload_history_text, R.id.code_history_text, R.id.logout_text, R.id.enter_code_text, R.id.flashlights_text, R.id.back_menu_img,
            R.id.scan_img, R.id.ensure_btn, R.id.back_text, R.id.bottom_menu_parent,R.id.content_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.upload_history_text:
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                }
                UploadHistoryActivity.startAction(mContext, upload_completed, false);
                break;
            case R.id.code_history_text:
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                }
                startActivity(InviteCodeHistoryActivity.class);
                break;
            case R.id.logout_text:
                MyApplication.getInstance().clearData();
                startActivity(LoginSelectActivity.class);
                finish();
                break;
            case R.id.enter_code_text:

                break;
            case R.id.flashlights_text:

                break;
            case R.id.back_menu_img:
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                } else {
                    menuParent.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.scan_img:
//                DataRequestUtil.getInstance(mContext).uploadImage(mContext,"8", "/storage/emulated/0/ysb/video/recording1206444299.mp4", new FileUploadCallBack() {
//                    @Override
//                    public void success(FileInfo fileInfo) {
//
//                    }
//                    @Override
//                    public void fail() {
//                        LoadingDialog.cancelDialogForLoading();
//                    }
//                });
                if (enterCodeParent.getVisibility() == View.VISIBLE) {
                    enterCodeParent.setVisibility(View.GONE);
                }
                startActivityForResult(QRScanActivity.class, 1000);
                break;
            case R.id.ensure_btn:

                break;
            case R.id.back_text:
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                } else {
                    menuParent.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.bottom_menu_parent:
                if (enterCodeParent.getVisibility() == View.VISIBLE) {
                    enterCodeParent.setVisibility(View.GONE);
                }
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                }
                break;
            case R.id.content_view:
                if (menuParent.getVisibility() == View.VISIBLE) {
                    menuParent.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String result = data.getStringExtra(QRScanActivity.EXTRA_QRCODE_SUCCESS);
            switch (requestCode) {
                case 1000:
                    if (result.equals("***")) {
                        showShortToast("扫描结果格式有误！");
                    } else {
                        InviteBoxInfoActivity.startAction(mContext, result);
                    }
                    break;
            }
        }
    }


    private void initBaiDuMap() {
        mapview.setFocusable(false);
        mBaiduMap = mapview.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListenner());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.overlook(0);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void getBatchCodeSuccess(InviteBatchInfo inviteBatchInfo) {
        orderNameText.setText(inviteBatchInfo.getTitle());
        orderCodeText.setText("订单编号：" + inviteBatchInfo.getOrder_sn());
        orderBatchText.setText("批次：" + inviteBatchInfo.getBatch_sn());
        orderNumText.setText("总件数：" + inviteBatchInfo.getPackage_num());
        upload_completed = inviteBatchInfo.getUpload_completed();
        if ("0".equals(upload_completed)){
            scanImg.setClickable(true);
            scanImg.setImageResource(R.mipmap.scan_icon);
            hintText.setText("您已登录"+tvTitle.getText().toString()+"身份，请扫描箱子上的二维码完成信息的上传");
        }else if ("1".equals(upload_completed)){
            hintText.setText("您本次操作已完成");
            scanImg.setClickable(false);
            scanImg.setImageResource(R.mipmap.scan_gray_icon);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mLocClient == null) return;
        if (mLocClient.isStarted()) {
            mLocClient.requestLocation();
        } else {
            mLocClient.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocClient != null)
            mLocClient.stop();
    }

    @Override
    public void getBatchCodeFail() {

    }

    @Override
    public void getPackageInfoSuccess(InvitePackageInfo invitePackageInfo) {
        showLongToast(invitePackageInfo.toString());
    }

    @Override
    public void getPackageInfoFail() {

    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mapview == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return false;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }
}
